package com.jisheng.xb.common;



import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



public class FTPUtils {
	private static Logger logger = LoggerFactory.getLogger(FTPUtils.class);
	private static final int PORT = 10081;
	private static final String IP ="139.129.93.213";
	private static final String USER_NAME = "lyh";
	private static final String PASSWORD = "liyaohua";
	public static final String ISO_8859_1 = "ISO-8859-1";
	public static final String FTP_FILE_PATH ="/home/lyh/ftpfile/";
	
	private OutputStream os = null;
	private FileInputStream is = null;
	
	public static final char FTP_PATH_CHAR = '/';
	private static  FTPUtils ftpUtils = null;
	
	private static FTPClient ftpClient = null;
	
	private FTPUtils(){
		
	}
	
	public static  FTPUtils getInstance(){
		if(ftpUtils==null){
			ftpUtils = new FTPUtils();
			init();
		}
		return ftpUtils;
	}
	
	@SuppressWarnings("finally")
	public static boolean  init(){
		 int reply; 
		 boolean bool = true;
		 try {
			ftpClient = new FTPClient();
			ftpClient.connect(IP, PORT);
			ftpClient.login(USER_NAME, PASSWORD);// 登录  
			reply = ftpClient.getReplyCode();  
			ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			if (!FTPReply.isPositiveCompletion(reply)) {  
	        	 ftpClient.disconnect();  
	        	 logger.info("ftp服务器连接失败！");
	        	 bool =  false;
	         } 
			int replySend = ftpClient.sendCommand("OPTS UTF8 ON");  
	        if (replySend == 200) { // UTF8 Command  
	        	ftpClient.setControlEncoding("UTF-8");  
	        } 
	        bool = false;
			logger.info("ftp服务器连接成功！");
		} catch (SocketException e) {
			logger.error(e.getMessage());  
		} catch (IOException e) {
			logger.error(e.getMessage());  
		}finally{
			return bool;
		}
	}
	
	/**
	 * 关闭FTP
	 * 
	 * */
	private void close(){
		if(ftpClient.isConnected()){
			try {
				ftpClient.logout();
				ftpClient.disconnect();
			} catch (IOException e) {
				logger.error(e.getMessage());  
			}
			
		}
	}
	
	public void uploadFileToFtpByIS(InputStream inputStream, String fileName) throws IOException {  
        ftpClient.storeFile(FTP_FILE_PATH+fileName, inputStream);  
    }  
  
    public File downFtpFile(String fileName, String localFileName) throws IOException {  
        File outfile = new File(localFileName);  
        OutputStream oStream = null;  
        try {  
            oStream = new FileOutputStream(outfile);  
            ftpClient.retrieveFile(FTP_FILE_PATH+fileName, oStream);  
            return outfile;  
        } finally {  
            if (oStream != null)  
                oStream.close();  
        }  
    }  
    
    
    /**
    * Description: 向FTP服务器上传文件
    * @Version1.0 Jul 27, 2008 4:31:09 PM by 崔红保（cuihongbao@d-heaven.com）创建
    * @param url FTP服务器hostname
    * @param port FTP服务器端口
    * @param username FTP登录账号
    * @param password FTP登录密码
    * @param path FTP服务器保存目录
    * @param filename 上传到FTP服务器上的文件名
    * @param input 输入流
    * @return 成功返回true，否则返回false
    */ 
    public static boolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) { 
        boolean success = false; 
        FTPClient ftp = new FTPClient(); 
        try { 
            int reply; 
            ftp.connect(url, port);//连接FTP服务器 
            //如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器 
            ftp.login(username, password);//登录 
            ftp.pwd();
            reply = ftp.getReplyCode(); 
            if (!FTPReply.isPositiveCompletion(reply)) { 
                ftp.disconnect(); 
                System.out.println("连接失败！");
                return success; 
            } else{
            	 System.out.println("连接成功！");
            }
            
            
            FTPFile[] files = ftp.listFiles(FTP_FILE_PATH);
            listFiles(files,ftp);
            
            //ftp.changeWorkingDirectory(path); 
            boolean bool = ftp.storeFile(filename, input); 
            System.out.println("是否保存成功："+bool);
            input.close(); 
            ftp.logout(); 
            success = true; 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } finally { 
            if (ftp.isConnected()) { 
                try { 
                    ftp.disconnect(); 
                } catch (IOException ioe) { 
                } 
            } 
        } 
        return success; 
    }
    
    
    private static void listFiles(FTPFile[] files,FTPClient ftp){
    	 for(FTPFile file : files){
         	if(file.isDirectory()){
         		try {
         			System.out.println("目录："+file.getName());
					FTPFile[] newFiles = ftp.listFiles(file.getName());
				} catch (IOException e) {
					System.out.println("出现错误！");
				}
         	}else{
         		System.out.println("文件："+file.getName());
         	}
         	
         }
    }
    
    
    
	
    /**
     * 上传文件
     * */
    public static void upload(){
    	File file2=new File("E:\\lyh\\vsftpd.txt");
    	FileInputStream input= null;
    	try {
			input = new FileInputStream(file2);
			FTPUtils.getInstance().uploadFileToFtpByIS(input,"vsftpd.txt");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    	
    }
   
	public static void main(String[] args){
		FileInputStream in;
		boolean isSuccess = false;
		try {
			in = new FileInputStream(new File("E:\\lyh\\vsftpd.txt"));
			isSuccess = uploadFile(IP, 10081, USER_NAME, PASSWORD, FTP_FILE_PATH, "1.txt", in);
			System.out.println(isSuccess);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		
	}

}
